//
//  LocalProductDetailViewController.m
//  SXH
//
//  Created by 房 国生 on 15/6/24.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "LocalProductDetailViewController.h"
#import "CommonService.h"

#import "HMSegmentedControl.h"
#import "UIImageView+WebCache.h"
#import "YYAnimationIndicator.h"
#import "TourismDetailsEntity.h"
#import "OrderEnsureViewController.h"
#import "LoginViewController.h"
#define k 7

@interface LocalProductDetailViewController ()<UIScrollViewDelegate,UIWebViewDelegate>
{
    YYAnimationIndicator *indicator;
}

//@property (nonatomic, strong) TourismDetailsEntity *tDetailEntity;
@property (nonatomic, strong) IBOutlet UIWebView *webViewContent;
@property (nonatomic, strong) IBOutlet UILabel *store_name;
@property (nonatomic, strong) IBOutlet UILabel *price;
@property (nonatomic, strong) IBOutlet UILabel *oldPrice;
@property (nonatomic, strong) IBOutlet UILabel *ship_cost;
@property (nonatomic, strong) IBOutlet UILabel *sale_count;
@property (nonatomic, strong) IBOutlet UILabel *address;

@property (strong, nonatomic) IBOutlet UIView *viewLocalProduct;
@property (weak, nonatomic) IBOutlet UIButton * btnShare;
@property (weak, nonatomic) IBOutlet UIButton * btnBack;
@property (weak, nonatomic) IBOutlet UIView *viewSegment;
@property (weak, nonatomic) IBOutlet UIView *viewNavigation;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollViewLocalProduct;
@property (weak, nonatomic) IBOutlet UIView *bottomBar;
@property (strong, nonatomic) HMSegmentedControl * segmentedControl2;
@property (weak, nonatomic) IBOutlet UILabel *storephone_label;//最下方电话号码label
@property NSString *store_phone;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pic_height;//顶部图片高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *wrapview_height;
@property (nonatomic, assign) CGFloat addlength;//segement增加的y值；
@property (weak, nonatomic) IBOutlet UIButton *buyBtn;
//add by cy 2015 11 04
@property (weak, nonatomic) IBOutlet UIView *wraperView;
@end

@implementation LocalProductDetailViewController
//@synthesize tDetailEntity;
@synthesize webViewContent;

@synthesize imageViewIcon, textViewContent;
@synthesize lpEntity;
@synthesize wrapEntity;
@synthesize viewLocalProduct,scrollViewLocalProduct,viewNavigation,viewSegment,bottomBar,segmentedControl2,wraperView;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"特产详情";
    
    viewLocalProduct.frame = CGRectMake(0, 0, self.view.bounds.size.width,768);
    [self.scrollViewLocalProduct addSubview:viewLocalProduct];
    scrollViewLocalProduct.contentSize = CGSizeMake(self.view.bounds.size.width, 768);
    scrollViewLocalProduct.delegate = self;
    webViewContent.delegate = self;
    viewNavigation.alpha = 0.0;
    
    self.pic_height.constant =  158/320.f*SCREEN_WIDTH;
    self.addlength = 158/320.f*SCREEN_WIDTH -158;
    self.wrapview_height.constant = self.addlength + 261;
    
    
    [self initViewController];
    segmentedControl2 = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"产品详情", @"产品参数", @"商品评价"]];
    
    [segmentedControl2 setIndexChangeBlock:^(NSUInteger index) {
        
        if (index == 0) {
//            NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:tDetailEntity.in_characteristic]];
//            [webViewContent loadRequest:request];
            NSString * urlString = lpEntity.product_introduce;
            NSURL *url = [NSURL URLWithString:urlString];
            NSData *data = [NSData dataWithContentsOfURL:url];
            NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSString * str2 = K_websiteStyleStr;
            NSString * str3 = [str2 stringByAppendingString:str];
            NSString *str4 = [str3 stringByAppendingString:@"</div>"];
            [webViewContent loadHTMLString:str4 baseURL:nil];
            
        } else if (index == 1) {
//            NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:tDetailEntity.in_tariff_description]];
//            [webViewContent loadRequest:request];
            
            NSString * urlString = self.lpEntity.product_attr;
            NSURL *url = [NSURL URLWithString:urlString];
            NSData *data = [NSData dataWithContentsOfURL:url];
            NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSString * str2 = K_websiteStyleStr;
            NSString * str3 = [str2 stringByAppendingString:str];
            NSString *str4 = [str3 stringByAppendingString:@"</div>"];
            [webViewContent loadHTMLString:str4 baseURL:nil];
            
        } else if (index == 2) {
//            NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:tDetailEntity.in_reservation_information]];
//            [webViewContent loadRequest:request];
            NSString * urlString = self.lpEntity.product_attr;
            NSURL *url = [NSURL URLWithString:urlString];
            NSData *data = [NSData dataWithContentsOfURL:url];
            NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSString * str2 = K_websiteStyleStr;
            NSString * str3 = [str2 stringByAppendingString:str];
            NSString *str4 = [str3 stringByAppendingString:@"</div>"];
            [webViewContent loadHTMLString:str4 baseURL:nil];
        }
        NSLog(@"Selected index %lu (via block)", (unsigned long)index);
    }];
    
    [segmentedControl2 setSelectionIndicatorHeight:4.0f];
    [segmentedControl2 setBackgroundColor:[UIColor whiteColor]];
    [segmentedControl2 setTextColor:[UIColor darkGrayColor]];
    [segmentedControl2 setSelectionIndicatorColor:[UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1]];
    [segmentedControl2 setSelectionIndicatorMode:HMSelectionIndicatorFillsSegment];
    [segmentedControl2 setSegmentEdgeInset:UIEdgeInsetsMake(0, 6, 0, 6)];
    [segmentedControl2 setCenter:CGPointMake(160, 120)];
    [segmentedControl2 setTag:2];
    segmentedControl2.frame = CGRectMake(7, 264 +self.addlength, SCREEN_WIDTH-k-k, 40);
    [self.view addSubview:segmentedControl2];
    [self getLPDetailData];
    
}
- (void) initViewController {
    
   
    
    NSString * urlString = lpEntity.product_introduce;
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    NSData *data = [NSData dataWithContentsOfURL:url];
//    NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//    NSString * str2 =@"<div id=\"content\" contenteditable=\"false\">";
//    NSString * str3 = [str2 stringByAppendingString:str];
//    NSString *str4 = [str3 stringByAppendingString:@"</div>"];
//    [webViewContent loadHTMLString:str4 baseURL:nil];
    [webViewContent loadRequest:request];
    
   }


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl {
    NSLog(@"Selected index %li (via UIControlEventValueChanged)", (long)segmentedControl.selectedIndex);
}

- (void) getLPDetailData
{
    indicator = [[YYAnimationIndicator alloc]initWithFrame:CGRectMake(ScreenWidth/2-40, ScreenHeight/2-40, 80, 57)];
    [indicator setLoadText:Loading_Text];
    [self.view addSubview:indicator];
    
    [indicator startAnimation];  //开始转动
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           wrapEntity.ID, @"id", nil];
    
    [service getNetWorkData:param
                       Path:LPDETAILPATH
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *) entity;
                      NSDictionary *dicContent = [dic objectForKey:@"row"];
                      
                      lpEntity = [[LPEntity alloc] init];
                      lpEntity = [lpEntity initWithAttributes:dicContent];
                      if ([lpEntity.can_sale intValue]) {
                          self.buyBtn.hidden = NO;
                      }
                      self.textViewContent.text = lpEntity.content;
                      
                      NSString *url = [NSString stringWithFormat:@"%@/%@", IMAGE_URL, lpEntity.album];
                      [self.imageViewIcon sd_setImageWithURL:[NSURL URLWithString:url]];
                      self.store_name.text = lpEntity.title;
                      _store_phone = lpEntity.store_phone;
                      self.price.text = lpEntity.price;
                      
                      self.ship_cost.text = lpEntity.ship_cost;
                      self.sale_count.text = lpEntity.sale_count;
                      self.address.text = lpEntity.address;
                      self.storephone_label.text = self.store_phone;
                      NSString *old_price = [NSString stringWithFormat:@"原价：%@元", lpEntity.old_price];
                      self.oldPrice.text = lpEntity.old_price;
                      NSUInteger length = [old_price length];
                      NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:old_price];
                      [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
                      
                      [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, length)];
                      [self.oldPrice setAttributedText:attri];
                      
                      //
                      //NSString * urlString = lpEntity.product_introduce;
                      NSString *urlString = @"http://upload.leyouss.com/html/specialty/info/770.html";
                      NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
                      NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                      NSString * str2 = K_websiteStyleStr;
                      NSString * str3 = [str2 stringByAppendingString:str];
                      NSString *str4 = [str3 stringByAppendingString:@"</div>"];
                      [webViewContent loadHTMLString:str4 baseURL:nil];
                      //
                      [indicator stopAnimationWithLoadText:HasLoaded_Text withType:YES];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                      [indicator stopAnimationWithLoadText:HasLoaded_Text withType:YES];
                  }];
}

- (IBAction)shareAction:(id)sender {
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.delegate = self;
    HUD.labelText = Loading_Hard_Text;
    
    NSArray* imageArray = [[NSArray alloc] initWithObjects:[imageViewIcon image], nil];
    
    [CommonService showShareActionSheet:self.view HUD:HUD
                             ImageArray:imageArray
                                    URL:PORTAL_URL
                                  Title:lpEntity.title
                                Content:lpEntity.price];
}

-(IBAction)buyItRightNow:(id)sender{
    
//    ALERT_ERR_MSG(@"此功能正在开发中");
    UserEntity *userEntity = [UserEntity sharedInstance];
    if (userEntity.login == NO) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    OrderEnsureViewController *vc = [[OrderEnsureViewController alloc] init];
    vc.lpEntity = lpEntity;
    vc.userEntity = userEntity;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y >0) {
        _btnBack.hidden = YES;
        //_btnSave.hidden = YES;
        _btnShare.hidden = YES;
        DebugLog(@"%f", scrollView.contentOffset.y/81.0);
        
        viewNavigation.alpha = 1.0*(scrollView.contentOffset.y/81.0);
        
        [self.view bringSubviewToFront:viewNavigation];
    } else {
        _btnBack.hidden = NO;
        //_btnSave.hidden = NO;
        _btnShare.hidden = NO;
        
        viewNavigation.alpha = 0.0;
    }
 
    
    segmentedControl2.frame = CGRectMake(k, 302 + self.addlength, self.view.bounds.size.width-2*k, 40);

    if (scrollView.contentOffset.y > 200 + self.addlength) {
        
      segmentedControl2.frame =CGRectMake(k, 61, self.view.bounds.size.width-2*k, 40);
    }
    else{
        
        segmentedControl2.frame = CGRectMake(k, wraperView.bounds.size.height+3-scrollView.contentOffset.y, self.view.bounds.size.width-2*k, 40);
    }
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGFloat documentHeight = [[webViewContent stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"content\").offsetHeight;"] floatValue];
    CGRect frame = webViewContent.frame;
    if (documentHeight < 424) {
        frame.size.height = 510;
        webViewContent.frame = frame;
        
        CGRect frame2 = scrollViewLocalProduct.frame;
        frame2.size.height = 766;
        scrollViewLocalProduct.contentSize = frame2.size;
        
        DebugLog(@"frame3.size.height = %f", frame2.size.height);
    } else {
        frame.size.height = documentHeight+43;
        webViewContent.frame = frame;
        
        
        DebugLog(@"documentHeight=%f, %f", documentHeight, webViewContent.scrollView.contentSize.height);
        
        CGRect frame2 = scrollViewLocalProduct.frame;
        
        frame2.size.height = documentHeight+350;
        scrollViewLocalProduct.contentSize = frame2.size;
        
        DebugLog(@"frame3.size.height = %f", frame2.size.height);
    }
    
}

- (IBAction)doCallPhone:(id)sender {
    
    if (_store_phone == nil || _store_phone.length == 0) {
        ALERT_ERR_MSG(NoTelNumber);
        return;
    }
    
    NSString *number = _store_phone;// 此处读入电话号码
    // NSString *num = [[NSString alloc] initWithFormat:@"tel://%@",number]; //number为号码字符串 如果使用这个方法 结束电话之后会进入联系人列表
    NSString *num = [[NSString alloc] initWithFormat:@"telprompt://%@",number]; //而这个方法则打电话前先弹框  是否打电话 然后打完电话之后回到程序中 网上说这个方法可能不合法 无法通过审核
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]]; //拨号
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"LocalProductDetailViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"LocalProductDetailViewController"];
}
@end
